package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.ApplicationVariable;
import com.example.demo.common.PasswordTools;
import com.example.demo.common.UserSessionTools;
import com.example.demo.entity.UserEntity;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/reg")
    public AjaxResult reg(UserEntity user) {
        // 1. 进行非空判断
        if (user == null || !StringUtils.hasLength(user.getUsername())
                || !StringUtils.hasLength(user.getPassword())) {
            return AjaxResult.fail(-1, "参数有误!");
        }
        // 2. 调用 UserService 进行添加操作, 并将返回的请求的结果添加到 AjaxResult.data 里
        // 将密码加盐加密
        user.setPassword(PasswordTools.encrypt(user.getPassword()));
        int res = userService.reg(user);
        return AjaxResult.success(res);
    }

    @RequestMapping("/login")
    public AjaxResult login(String username, String password, HttpServletRequest req) {
        if (!StringUtils.hasLength(username)
                || !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1, "参数有误!");
        }
        UserEntity user = userService.login(username);
        if (user == null || user.getId() <= 0) {
            return AjaxResult.fail(-2, "用户名或密码错误!");
        }

        if (!PasswordTools.decrypt(password, user.getPassword())) {
            return AjaxResult.fail(-2, "用户名或密码错误!");
        }

        // 将当前登录的信息存储到 session 中
        HttpSession session = (HttpSession) req.getSession(true);
        session.setAttribute(ApplicationVariable.SESSION_KEY_USERINFO, user);
        return AjaxResult.success(1);
    }

    @RequestMapping("/logout")
    public AjaxResult logout(HttpServletRequest req) {
        HttpSession session = req.getSession(false);

        session.removeAttribute(ApplicationVariable.SESSION_KEY_USERINFO);
        return AjaxResult.success(1);
    }

    @RequestMapping("/islogin")
    public AjaxResult isLogin(HttpServletRequest req) {
        UserEntity user = UserSessionTools.getLoginUser(req);
        if (user == null) {
            // 未登录
            return AjaxResult.success(0);
        } else {
            return AjaxResult.success(1);
        }
    }
}
